# -*- coding: utf-8 -*-            
# @Author : HJH
# @Time : 2024/8/11 16:52
# @Use :
from datetime import timedelta, datetime

import pandas as pd
from tqdm import tqdm
from loguru import logger
import concurrent.futures
from api.tongc_policy_api import parity_oneway_query


def task_function(data_dict):
    res_data_list = parity_oneway_query(data_dict)['data']
    if res_data_list is None:
        # 更新进度条
        progress_bar.update(1)
        return

    res_data = [rd for rd in res_data_list if rd['cabinCode'] in 'P']
    if len(res_data) < 1:
        # 更新进度条
        progress_bar.update(1)
        return
    res_data = res_data[0]
    r_p_excel_df.at[data_dict.name, 'winState'] = res_data['winState']
    r_p_excel_df.at[data_dict.name, 'cabinMinFdPrice'] = res_data['cabinMinFdPrice']
    r_p_excel_df.at[data_dict.name, 'cabinCode'] = res_data['cabinCode']
    r_p_excel_df.at[data_dict.name, 'minPrice'] = res_data['minPrice']
    r_p_excel_df.at[data_dict.name, 'policyId'] = res_data['policyId']
    r_p_excel_df.at[data_dict.name, 'selfMinPrice'] = res_data['selfMinPrice']
    r_p_excel_df.at[data_dict.name, 'source'] = res_data['source']

    # 更新进度条
    progress_bar.update(1)


if __name__ == '__main__':
    # 读取excel文件
    r_p_excel_file = pd.ExcelFile('../docs/bj/KN-P.xlsx')
    # 读取指定Sheet数据
    r_p_excel_df = r_p_excel_file.parse('Sheet1')
    # data_dict_list = r_p_excel_df.to_dict(orient='records')
    # start_date = datetime.now().date()
    # end_date = datetime.now().date() + timedelta(days=62)
    # res_list = []
    # for item in data_dict_list:
    #     current_date = start_date
    #     while current_date <= end_date:
    #         new_item = dict()
    #         new_item['出发'] = item['出发']
    #         new_item['到达'] = item['到达']
    #         new_item['出发日期'] = current_date.strftime("%Y-%m-%d")
    #         res_list.append(new_item)
    #
    #         current_date += timedelta(days=1)
    #
    # # 将列表转换为 DataFrame
    # df = pd.DataFrame(res_list)
    #
    # # # 设置表头
    # # header = ['航班号', '出发日期', '']
    #
    # print("开始写入文件... ...")
    # # 将数据写入 Excel 文件并设置表头
    # with pd.ExcelWriter(fr'../docs/bj/KN-P.xlsx', engine='xlsxwriter') as writer:
    #     df.to_excel(writer, index=False, )
    #
    # # 输出成功提示
    # print("Excel 文件写入成功！")

    # data_dict_list = data_dict_list[:20]

    total_rows = len(r_p_excel_df)

    # 创建进度条
    progress_bar = tqdm(total=total_rows, desc="执行进度", unit="次")

    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        for index, item in r_p_excel_df.iterrows():
            # task_function(row)
            executor.submit(task_function, item)

    # 关闭进度条
    progress_bar.close()

    logger.info("开始生成excel文件...")
    r_p_excel_df.to_excel(r'../docs/bj/同程比价记录-ALL2.xlsx', index=False)

    # 输出成功提示
    print("Excel 文件写入成功！")
